<template>
  <div class="event-driven-config">
    <el-form :model="form" label-width="120px">
      <el-form-item label="任务描述" prop="appId">
        <el-input
          v-model="form.jobDesc"
          placeholder="请输入任务描述"
        ></el-input>
      </el-form-item>

      <el-form-item label="CRON表达式" prop="cronExpression">
        <el-input
          v-model="form.cronExpression"
          placeholder="请输入CRON表达式"
        />
      </el-form-item>

      <el-form-item label="执行参数">
        <el-input
          v-model="form.executionParam"
          type="textarea"
          :rows="3"
          placeholder="输入JSON格式参数"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="eventList" style="width: 90%; float: right" border>
      <el-table-column
        prop="jobDesc"
        label="任务描述"
        width="180"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="triggerStatus"
        label="运行状态"
        width="100"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag :type="scope.row.triggerStatus === 1 ? 'success' : 'danger'">
            {{ scope.row.triggerStatus === 1 ? "running" : "stop" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="scheduleConf"
        label="CRON表达式"
        width="180"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="executorParam"
        label="执行参数"
        align="center"
      ></el-table-column>
      <el-table-column
        align="center"
        :label="$t('operation')"
        width="119px"
        fixed="right"
      >
        <template v-slot="scope">
          <div>
            <div>
              <div style="margin-right: 10px">
                <a
                  href="javascript:void(0)"
                  class="font-blue"
                  @click="startEvent(scope.row.id)"
                  >{{ $t("run") }}</a
                >
              </div>
              <div style="margin-right: 10px">
                <a
                  href="javascript:void(0)"
                  class="font-blue"
                  @click="stopEvent(scope.row.id)"
                  >{{ $t("stop") }}</a
                >
              </div>
              <div style="margin-right: 10px">
                <a
                  href="javascript:void(0)"
                  class="font-blue"
                  @click="editEvent(scope.row.id)"
                  >{{ $t("edit") }}</a
                >
              </div>
              <div style="margin-right: 10px">
                <a
                  href="javascript:void(0)"
                  class="font-blue"
                  @click="deleteEvent(scope.row.id)"
                  >{{ $t("delete") }}</a
                >
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="编辑事件" :visible.sync="editDialogVisible">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="任务描述" prop="jobDesc">
          <el-input v-model="editForm.jobDesc" placeholder="请输入任务描述" />
        </el-form-item>
        <el-form-item label="CRON表达式" prop="cronExpression">
          <el-input v-model="editForm.cronExpression" />
        </el-form-item>
        <el-form-item label="执行参数">
          <el-input
            v-model="editForm.executorParam"
            type="textarea"
            :rows="3"
            placeholder="输入JSON格式参数"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllEvent,
  addEvent,
  updateEvent,
  removeEvent,
  startEvent,
  stopEvent,
} from "@/api/tool";

export default {
  data() {
    return {
      form: {
        jobDesc: "",
        author: "admin",
        cronExpression: "",
        executionParam: "",
      },
      eventList: [],
      editDialogVisible: false,
      editForm: {
        id: "",
        jobDesc: "",
        cronExpression: "",
        executorParam: "",
      },
    };
  },

  created() {
    this.freshList();
  },

  methods: {
    freshList() {
      getAllEvent()
        .then((response) => {
          console.log(response);
          if (response != null) {
            this.eventList = response.data;
          } else {
            this.$message({
              message: "获取事件列表失败",
              type: "error",
            });
          }
        })
        .catch((error) => {
          console.log("error: " + error);
        });
    },
    submitForm() {
      if (!this.validateCron()) {
        return;
      }
      const formData = new FormData();
      formData.append("jobDesc", this.form.jobDesc);
      formData.append("author", this.form.author);
      formData.append("scheduleConf", this.form.cronExpression);
      formData.append("schedule_conf_CRON", this.form.cronExpression);
      formData.append("executorParam", this.form.executionParam);
      formData.append("glueSource", this.form.executionParam);

      addEvent(formData)
        .then((response) => {
          if (response.code === 200) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.freshList();
          } else {
            this.$message({
              message: "添加失败",
              type: "error",
            });
          }
          this.resetForm();
        })
        .catch((error) => {
          console.log("error: " + error);
        });
    },

    resetForm() {
      this.form = {
        jobDesc: "",
        cronExpression: "",
        executionParam: "",
      };
    },

    validateCron() {
      const cron = this.form.cronExpression.trim();
      const cronRegex =
        /^(\*|([0-9]{1,2})|(?:[0-9]{1,2}(\/|-)[0-9]{1,2})|(?:\*\/[0-9]{1,2}))\s+(\*|([0-9]{1,2})|(?:[0-9]{1,2}(\/|-)[0-9]{1,2})|(?:\*\/[0-9]{1,2}))\s+(\*|([0-9]{1,2})|(?:[0-9]{1,2}(\/|-)[0-9]{1,2})|(?:\*\/[0-9]{1,2}))\s+(\*|([1-9]|1[0-2])|(?:[1-9]|1[0-2](\/|-)[1-9]|1[0-2])|(?:\*\/[1-9]|1[0-2]))\s+(\*|([1-9]|[12][0-9]|3[01])|(?:[1-9]|[12][0-9]|3[01](\/|-)[1-9]|[12][0-9]|3[01])|(?:\*\/[1-9]|[12][0-9]|3[01]))\s+(\?|\*|([0-6])|(?:[0-6](\/|-)[0-6])|(?:\*\/[0-6]))$/;

      if (cronRegex.test(cron)) {
        return true;
      } else {
        this.$message.error("Cron 表达式格式不正确，请检查后重新输入！");
        return false;
      }
    },

    editEvent(id) {
      const task = this.eventList.find((item) => item.id === id);
      if (task) {
        console.log(task);
        this.editForm = {
          id: task.id,
          jobDesc: task.jobDesc,
          cronExpression: task.scheduleConf,
          executorParam: task.executorParam,
        };
        this.editDialogVisible = true;
      }
    },

    async saveEdit() {
      try {
        // 调用验证Cron
        // if (!this.validateCron()) {
        //   this.$message.error("Cron 表达式格式不正确，请检查后重新输入！");
        //   return;
        // }
        const response = await updateEvent(this.editForm);
        if (response.code === 200) {
          this.$message.success("修改成功");
          this.freshList();
          this.editDialogVisible = false;
        } else {
          this.$message.error(response.msg || "修改失败");
        }
      } catch (error) {
        console.error("保存失败:", error);
        this.$message.error("请求失败，请检查网络");
      }
    },

    startEvent(id) {
      this.$confirm("是否要启动该任务?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        startEvent(id)
          .then((response) => {
            console.log(response);
            if (response.code === 200) {
              this.$message.success("启动成功");
              this.freshList();
            }
          })
          .catch((error) => {
            console.error("启动失败:", error);
            this.$message.error("启动失败");
          });
      });
    },

    stopEvent(id) {
      this.$confirm("是否要停止该任务?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        stopEvent(id)
          .then((response) => {
            console.log(response);
            if (response.code === 200) {
              this.$message.success("停止成功");
              this.freshList();
            }
          })
          .catch((error) => {
            console.error("停止失败:", error);
            this.$message.error("停止失败");
          });
      });
    },

    deleteEvent(id) {
      this.$confirm("此操作将永久删除该任务, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeEvent(id)
            .then((response) => {
              if (response.code === 200) {
                this.$message.success("删除成功");
                this.freshList();
              }
            })
            .catch((error) => {
              console.error("删除失败:", error);
              this.$message.error("删除失败");
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
  },
};
</script>

<style scoped>
.event-driven-config {
  padding: 20px;
}
.el-form {
  margin-bottom: 30px;
}
.el-table {
  margin-top: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>